package org.southyin.securitysamples.service;

import org.southyin.securitysamples.mapper.LoginMapper;
import org.southyin.securitysamples.model.Role;
import org.southyin.securitysamples.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class LoginService implements UserDetailsService {
    @Autowired
    LoginMapper loginMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 跟据用户名查找用户
        User user = loginMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roles = loginMapper.getRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }
}
